import {
  DynamicModule,
  Global,
  Module,
  Inject,
  OnModuleDestroy,
} from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import {
  WechatModuleAsyncOptions,
  WechatModuleOptions,
} from './wechat.interface';
import {
  createAsyncClientOptions,
  createClient,
  WechatClient,
} from './wechat-client.provider';

import { WECHAT_MODULE_OPTIONS, WECHAT_CLIENT } from './wechat.constants';
import { WechatService } from './wechat.service';
import { WechatAuthService } from './wechat-auth.service';

@Global()
@Module({
  providers: [WechatService, WechatAuthService],
  exports: [WechatService, WechatAuthService],
})
export class WechatCoreModule {
  constructor(
    @Inject(WECHAT_MODULE_OPTIONS)
    private readonly options: WechatModuleOptions | WechatModuleOptions[],
    private readonly moduleRef: ModuleRef,
  ) {}

  static register(
    options: WechatModuleOptions | WechatModuleOptions[],
  ): DynamicModule {
    return {
      module: WechatCoreModule,
      providers: [
        createClient(),
        { provide: WECHAT_MODULE_OPTIONS, useValue: options },
      ],
      // exports: [WechatService],
    };
  }

  static forRootAsync(options: WechatModuleAsyncOptions): DynamicModule {
    return {
      module: WechatCoreModule,
      imports: options.imports,
      providers: [createClient(), createAsyncClientOptions(options)],
      // exports: [WechatService],
    };
  }
}
